package com.guslegend.service.impl;

import com.guslegend.controller.request.AccountLoginRequest;
import com.guslegend.controller.request.AccountRegisterRequest;
import com.guslegend.enums.AuthTypeEnum;
import com.guslegend.enums.BizCodeEnum;
import com.guslegend.enums.SendCodeEnum;
import com.guslegend.manager.AccountManager;
import com.guslegend.model.AccountDO;
import com.guslegend.model.LoginUser;
import com.guslegend.service.AccountService;
import com.guslegend.service.NotifyService;
import com.guslegend.utils.CommonUtils;
import com.guslegend.utils.IDUtil;
import com.guslegend.utils.JWTUtil;
import com.guslegend.utils.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jcajce.provider.digest.MD5;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

    @Autowired
    private NotifyService notifyService;
    @Autowired
    private AccountManager accountManager;

    /**
     *   手机验证码验证
     *   密码加密（TODO）
     *   账号唯一性检查（TODO）
     *   插入数据库
     *   新注册用户福利发放（TODO）
     * @param registerRequest
     * @return
     */
    @Override
    public JsonData register(AccountRegisterRequest registerRequest) {

        boolean checkCode=false;
        //判断验证码
        if (StringUtils.isNotBlank(registerRequest.getPhone())){
            checkCode=notifyService.checkCode(SendCodeEnum.USER_REGISTER,registerRequest.getPhone(), registerRequest.getCode());
        }
        //验证码错误
        if (!checkCode){
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }

        AccountDO accountDO=new AccountDO();
        BeanUtils.copyProperties(registerRequest,accountDO);
        //认证级别
        accountDO.setAuth(AuthTypeEnum.DEFAULT.name());
        //生成唯一账号
        accountDO.setAccountNo(Long.valueOf(IDUtil.geneSnowFlakeID().toString()));
        //密码设置 秘钥 盐
        accountDO.setSecret("$1$"+ CommonUtils.getStringNumRandom(8));
        String cryptPwd= Md5Crypt.md5Crypt(registerRequest.getPwd().getBytes(),accountDO.getSecret());
        accountDO.setPwd(cryptPwd);

        int rows=accountManager.insert(accountDO);
        log.info("rows:{},注册成功:{}",rows,accountDO);
        //用户注册成功,发放福利 TODO
        userRegisterInitTask(accountDO);

        return JsonData.buildSuccess();
    }

    /**
     * 1.根据手机号查找
     * 2.
     * @param request
     * @return
     */
    @Override
    public JsonData login(AccountLoginRequest request) {

        List<AccountDO> accountDOList = accountManager.findByPhone(request.getPhone());
        if (accountDOList!=null&&accountDOList.size()==1){

            AccountDO accountDO = accountDOList.get(0);
            String md5Crypt = Md5Crypt.md5Crypt(request.getPwd().getBytes(), accountDO.getSecret());
            if (md5Crypt.equalsIgnoreCase(accountDO.getPwd())){

                LoginUser loginUser=LoginUser.builder().build();
                BeanUtils.copyProperties(accountDO,loginUser);
                //生成TOKEN
                String token = JWTUtil.gengJsonWebToken(loginUser);
                return JsonData.buildSuccess(token);
            }else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }

        }else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }

    }

    /**
     * 用户初始化,发放福利: 流量包 TODO
     * @param accountDO
     */
    private void userRegisterInitTask(AccountDO accountDO){

    }
}
